import time

from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from base import login
from prefect import task, flow


# @task
def task_login():
    options = Options()
    options.add_experimental_option("detach", True)
    options.add_argument("--start-maximized")
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-dev-shm-usage')
    options.add_argument('"--headless"')
    # driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()), options=options)
    driver = webdriver.Remote(command_executor='http://47.92.231.23:9516/wd/hub', options=options)
    driver.implicitly_wait(10)

    web = WebDriverWait(driver, 10, 2)
    # hvpp登录
    params = {
        "url": "https://h-vpp-test.techstar.com.cn/login",
        "username": "dcgly",
        "password": "Keeper@Techstar3",
        "files:": "screenshots",
    }
    result = login(driver, web, **params)
    print(result)
    # driver.execute_script(f"window.localStorage.setItem('{key}', '{value}')")
    HiTMG = driver.execute_script(f"return window.localStorage.getItem('H-iTMG')")
    token = driver.execute_script(f"return window.localStorage.getItem('token')")
    driver.close()
    return result


@flow(log_prints=True)
def hvpp():
    token = task_login()
    print(f"Token: {token}")


@task
def run_selenium_test(url, node_index):
    desired_cap = DesiredCapabilities.CHROME.copy()
    desired_cap["platform"] = "ANY"
    options = Options()
    options.add_experimental_option("detach", True)
    options.add_argument("--start-maximized")
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-dev-shm-usage')
    options.add_argument('"--headless"')
    # Connect to the Selenium Grid using the provided node index
    driver = webdriver.Remote(
        command_executor=f"http://172.16.62.160:4444/wd/hub",
        options=options,
    )

    driver.get(url)
    print(driver.title)
    # Perform your Selenium operations here
    # ...
    driver.quit()


@flow(log_prints=True)
def demo():
    test_results = run_selenium_test.map(
        ["http://www.baidu.com", "https://www.techstar.com.cn/home/#/", "https://www.taosdata.com/"],
        node_index=[0, 1, 1])


@task
def process_item(item):
    # 在这里实现对单个 item 的处理逻辑
    result = item * 2
    print(result)
    time.sleep(10)
    return result

@task
def process_noitem():
    print('hello')
    time.sleep(10)
    return

@flow(log_prints=True)
def flow_process_item():
    items = [1, 2, 3, 4, 5]  # 要并行处理的数据列表
    processed_items = process_item.map(items)
    process_noitem()


if __name__ == '__main__':
    # get_token()
    # task_login()
    # demo()
    flow_process_item()
